<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="校区" prop="campusId">
        <el-select v-model="queryParams.campusId" placeholder="请选择校区" clearable>
          <el-option v-for="item in campusList" :key="item.value" :label="item.campusName"
            :value="item.campusId" />
        </el-select>
      </el-form-item>
      <el-form-item label="艺术家" prop="stuName">
        <el-input v-model="queryParams.stuName" placeholder="艺术家" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="作品名" prop="artworkTitle">
        <el-input v-model="queryParams.artworkTitle" placeholder="请输入作品名" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="artworkStatus">
        <el-select v-model="queryParams.artworkStatus" placeholder="请选择状态" clearable>
          <el-option v-for="dict in dict.type.art_works_status" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="作品类型" prop="typeName">
        <el-select v-model="queryParams.typeName" placeholder="请输入作品类型" clearable>
          <el-option v-for="item in typeList" :key="item.value" :label="item.typeName"
            :value="item.typeName" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['artworks:artworks:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['artworks:artworks:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['artworks:artworks:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['artworks:artworks:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="artworksList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="作品ID" align="center" prop="artworksId" />
      <el-table-column label="关联艺术家ID" align="center" prop="stuName" />
      <el-table-column label="作品名" align="center" prop="artworkTitle" />
      <el-table-column label="作品图片" align="center" prop="artworkLink" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.artworkLink" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="作品描述" align="center" prop="artworkContent" />
      <el-table-column label="状态" align="center" prop="artworkStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.art_works_status" :value="scope.row.artworkStatus" />
        </template>
      </el-table-column>
      <el-table-column label="作品类型" align="center" prop="typeName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['artworks:artworks:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['artworks:artworks:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改校区作品管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="作品名" prop="artworkTitle">
          <el-input v-model="form.artworkTitle" placeholder="请输入作品名" />
        </el-form-item>
        <el-form-item label="作品图片" prop="artworkLink">
          <el-upload class="upload-demo" drag action :multiple="false" :http-request="uploadImg"
            :show-file-list="false">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>

          <!-- 图片预览区域 -->
          <div v-if="form.artworkLink" class="image-preview" style="max-width: 200px; margin-top: 10px;">
            <img :src="form.artworkLink" alt="预览图" class="preview-image" style="width: 100%; max-height: 120px; object-fit: contain;">
          </div>
        </el-form-item>
        <!-- <el-form-item label="作品图片" prop="artworkLink">
          <image-upload v-model="form.artworkLink" />
        </el-form-item> -->
        <el-form-item label="作品描述">
          <editor v-model="form.artworkContent" :min-height="192" />
        </el-form-item>
        <el-form-item label="状态" prop="artworkStatus">
          <el-radio-group v-model="form.artworkStatus">
            <el-radio v-for="dict in dict.type.art_works_status" :key="dict.value"
              :label="parseInt(dict.value)">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="作品类型" prop="typeName">
        <el-select v-model="form.typeId" placeholder="请输入作品类型" clearable>
          <el-option v-for="item in typeList" :key="item.value" :label="item.typeName"
            :value="item.typeId" />
        </el-select>
      </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listArtworks, getArtworks, delArtworks, addArtworks, updateArtworks,selectTypeList } from "@/api/artworks/artworks"
import { uploadIdCard } from "@/api/artGood/artGood"
import { listAllCampus } from '@/api/course/courseParent'

export default {
  name: "Artworks",
  dicts: ['art_works_status'],
  data() {
    return {

      // 校区
      campusList: [],

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 校区作品管理表格数据
      artworksList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 类型
      typeList:[],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        stuName: null,
        artworkTitle: null,
        artworkStatus: null,
        typeName: null,
        campusId:null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        artworkTitle: [
          { required: true, message: "作品名不能为空", trigger: "blur" }
        ],
        artworkStatus: [
          { required: true, message: "状态(0:下架 1:上架)不能为空", trigger: "change" }
        ],
      }
    }
  },
  created() {
    this.getList()
    this.getTypeList()
    this.getCampusList()
  },
  methods: {
    /** 查询校区作品管理列表 */
    getList() {
      this.loading = true
      listArtworks(this.queryParams).then(response => {
        this.artworksList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    getTypeList(){
      selectTypeList().then(res =>{
        console.log(res,999)
        this.typeList = res.data
        console.log(this.typeList,888)
      })
    },
    // 查询校区
    getCampusList(){
      listAllCampus().then(res => {
        this.campusList = res.data || []
        console.log(this.campusList, 999)
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        artworksId: null,
        stuName: null,
        artworkTitle: null,
        artworkLink: null,
        artworkLink: null,
        artworkContent: null,
        artworkStatus: null,
        artworkCreateTime: null,
        artworkUpdateTime: null,
        campusId: 1,
        demo2: null,
        demo3: null,
        typeName: null,
        typeId: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.artworksId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加校区作品管理"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const artworksId = row.artworksId || this.ids
      getArtworks(artworksId).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改校区作品管理"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.artworksId != null) {
            console.log(this.form, 8999)
            updateArtworks(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addArtworks(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const artworksIds = row.artworksId || this.ids
      this.$modal.confirm('是否确认删除校区作品管理编号为"' + artworksIds + '"的数据项？').then(function () {
        return delArtworks(artworksIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => { })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('artworks/artworks/export', {
        ...this.queryParams
      }, `artworks_${new Date().getTime()}.xlsx`)
    },


     // 上传图片，修改图片
     uploadImg(item) {
      const formData = new FormData();
      formData.append("file", item.file);

      uploadIdCard(formData)
        .then(res => {
          this.$modal.msgSuccess("上传成功");
          // 直接赋值给表单的goodPicture字段
          this.form.artworkLink = res.data.file.url;
          console.log('图片URL已保存到表单:', this.form.artworkLink);

          // 可选：上传成功后显示预览
          this.previewImage = res.data.file.url;
        })
        .catch(error => {
          this.$modal.msgError("上传失败: " + error.message);
          console.error('图片上传失败:', error);
        });
    },

  }
}
</script>
